package com.gesonet.common.utils;

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * @Description: 邮件发送
 * @author QXX
 * @date 2014年11月6日 上午9:54:14
 */
public class SimpleMailSender {
	
	private static final Logger LOG = LoggerFactory.getLogger(SimpleMailSender.class);
	
	private static final String MAIL_SERVER_HOST = PropertiesUtils.getString("mail.server.host", "smtp.ym.163.com");
	private static final String MAIL_SERVER_PORT = PropertiesUtils.getString("mail.server.port", "25");
	private static final String SYSTEM_MAIL_USER = PropertiesUtils.getString("system.mail.user", "admin@edaox.com");
	private static final String SYSTEM_MAIL_PWD = PropertiesUtils.getString("system.mail.pwd", "yidaodianjin");
	
	
	// 发送邮件的服务器的IP和端口      
    private String mailServerHost;
    private String mailServerPort;  
	// 邮件发送者的地址
	private String fromAddress;
	// 邮件接收者的地址
	private String toAddress;
	// 邮件抄送者的地址
	private String ccAddress;
	// 登陆邮件发送服务器的用户名和密码
	private String userName;
	private String password;
	// 是否需要身份验证
	private boolean validate = true;
	// 邮件主题
	private String subject;
	// 邮件的文本内容
	private String content;
	
	private File attachment;

	/**
	 * 系统邮件发送
	 * @param toAddr 接收地址
	 * @param subject 主题
	 * @param content 内容
	 */
	public SimpleMailSender(String toAddr,String subject,String content){
		this.mailServerHost = MAIL_SERVER_HOST;
		this.mailServerPort = MAIL_SERVER_PORT;
		this.fromAddress = SYSTEM_MAIL_USER;
		this.userName = SYSTEM_MAIL_USER;
		this.password = SYSTEM_MAIL_PWD;
		this.toAddress = toAddr;
		this.subject = subject;
		this.content = content;
	}
	
	public SimpleMailSender(String host, String port, String fromAddr, String user, String pwd, String _subject,String _content,String _toUser,String _ccUser) {
		this.mailServerHost = host;
		this.mailServerPort = port;
		this.fromAddress = fromAddr;
		this.userName = user;
		this.password = pwd;
		this.toAddress = _toUser;
		this.ccAddress = _ccUser;
		this.subject = _subject;
		this.content = _content;
	}
	
	/**
	 * 带附件的邮件发送
	 * @param host
	 * @param port
	 * @param fromAddr
	 * @param user
	 * @param pwd
	 * @param _subject
	 * @param _content
	 * @param _toUser
	 * @param _ccUser
	 * @param attachment
	 */
	public SimpleMailSender(String host, String port, String fromAddr, String user, String pwd, String _subject,String _content,String _toUser,String _ccUser,File attachment) {
		this.mailServerHost = host;
		this.mailServerPort = port;
		this.fromAddress = fromAddr;
		this.userName = user;
		this.password = pwd;
		this.toAddress = _toUser;
		this.ccAddress = _ccUser;
		this.subject = _subject;
		this.content = _content;
		this.attachment = attachment;
	}

	
	class MyAuthenticator extends Authenticator{   
	    String userName=null;   
	    String password=null;   
	        
	    public MyAuthenticator(){   
	    }   
	    public MyAuthenticator(String username, String password) {    
	        this.userName = username;    
	        this.password = password;    
	    }    
	    @Override
	    protected PasswordAuthentication getPasswordAuthentication(){   
	        return new PasswordAuthentication(userName, password);   
	    }   
	}

	
	public boolean sendMail() {
		
		try {
			//必填信息非空验证
			if(StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(toAddress)){
				LOG.info("one of needed paramter is blank,userName is {},password is {},toAddress is {}", userName, password, toAddress);
				return false;
			}
			MyAuthenticator  authenticator = null;
			Properties pro = this.getProperties();
			if (validate) {
				// 如果需要身份认证，则创建一个密码验证器
				authenticator = new MyAuthenticator(userName,password);
			}
			// 根据邮件会话属性和密码验证器构造一个发送邮件的session      
			Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
			// 根据session创建一个邮件消息   
			Message mailMessage=new MimeMessage(sendMailSession);
			// 创建邮件发送者地址 
			Address from =new InternetAddress(this.fromAddress);
			// 设置邮件消息的发送者
			mailMessage.setFrom(from);
			// 创建邮件的接收者地址，并设置到邮件消息中
			mailMessage.setRecipients(Message.RecipientType.TO,getAddress(this.toAddress));
			//创建邮件的抄送者地址，并设置到邮件消息中
			if(org.apache.commons.lang3.StringUtils.isNotBlank(ccAddress)){
	    	  mailMessage.setRecipients(Message.RecipientType.CC,getAddress(this.ccAddress));
			}
			// 设置邮件消息的主题  
			mailMessage.setSubject(this.subject);
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(new Date());
	      	// 设置邮件消息的主要内容  
//			mailMessage.setContent(content,"text/html; charset=utf-8");
			
			Multipart multipart = new MimeMultipart();
			BodyPart contentPart = new MimeBodyPart();
			contentPart.setContent(content, "text/html; charset=utf-8");
			multipart.addBodyPart(contentPart);
			if (attachment != null) {
				BodyPart attachmentBodyPart = new MimeBodyPart();
				DataSource source = new FileDataSource(attachment);
				attachmentBodyPart.setDataHandler(new DataHandler(source));
				//可以避免文件名乱码
				attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
				multipart.addBodyPart(attachmentBodyPart);
			}
			mailMessage.setContent(multipart);
			mailMessage.saveChanges();
			// 发送邮件
			Transport.send(mailMessage);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			LOG.info("邮件发送失败！失败日志：");
			return false;
		}
	}
	/**
	 * @author QXX
	 * @date 2014年11月6日 上午11:20:43
	 * @Description: 处理多个收件人或抄送人，装入数组 
	 * @param address
	 * @return
	 * @throws AddressException
	 * @throws
	 */
	public Address[] getAddress(String address){
			String[] froms=address.split(",");
			Address[] addres=new Address[froms.length];
			for(int i=0;i<froms.length;i++){
				try {
					Address from =new InternetAddress(froms[i]);
					addres[i]=from;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return addres;
	}
	
	 /**    
     * 获得邮件会话属性    
     */      
   public Properties getProperties(){      
     Properties p = System.getProperties();      
     p.put("mail.smtp.host",this.mailServerHost);      
     p.put("mail.smtp.port", this.mailServerPort);      
     p.put("mail.smtp.auth", validate ? "true" : "false");      
     return p;      
   }
   
   public static void main(String[] args) {
	new SimpleMailSender("305694695@qq.com", "ceshi", "cehis").sendMail();
}
}